package com.example.login;

import jakarta.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

@RestController
    @RequestMapping("/user")
public class UserController {

    @RequestMapping("/login")
    public Boolean login(String userName, String password, HttpSession session) {
        //参数校验
//        if(userName == null || userName.length() == 0
//            || password == null || password.length() == 0) {
//            return false;
//        }
        //Spring MVC 提供了更方便写法
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return false;
        }
        //判断账户密码是否正确
        //上面已经做了判空处理，userName不会为空，但下面的写法也是一种习惯
        if("admin".equals(userName) && "admin".equals(password)) {
            session.setAttribute("userName", userName);
            return true;
        }
        return false;
    }
    @RequestMapping("/index")
    //两种写法
//    public String getUserName(HttpSession session) {
//        return (String) session.getAttribute("userName");
//    }
    public String getUserName(@SessionAttribute("userName") String userName) {
        return userName;
    }
}
